package com.seguim.logging;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Logger {
	public static String dir;

	String classname;

	public Logger(String classname) {
		this.classname = classname;
		write("CREATED at " + getDate());
	}

	public static Logger getLogger(String classname, String dirTmp) {
		dir = dirTmp;
		return new Logger(classname);
	}

	public static Logger getLogger(String classname) {
		return new Logger(classname);
	}

	private void write(String message) {
		try {
			FileWriter fw = new FileWriter(dir + System.getProperty("file.separator") + "seguim.log", true);
			fw.write("[" + classname + "] " + message + "\n");
			fw.flush();
			fw.close();
		} catch (IOException ioex) {
			ioex.printStackTrace();
		}
	}

	public void debug(String message) {
		write("[DEBUG] " + getDate() + " - " + message);
	}

	public void info(String message) {
		write("[INFO] " + getDate() + " - " + message);
	}

	public void warn(String message) {
		write("[WARN] " + getDate() + " - " + message);
	}

	public void error(String message) {
		write("[ERROR] " + getDate() + " - " + message);
	}

	public void error(String message, Throwable t) {
		write("[ERROR] " + getDate() + " - " + message + "::" + stack2string(t));
	}

	private String getDate() {
		Date lm = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", new Locale("en"));
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		return "[" + sdf.format(lm) + "]";
	}

	private String stack2string(Throwable t) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			t.printStackTrace(pw);
			return "------\r\n" + sw.toString() + "------\r\n";
		} catch (Exception e2) {
			return "bad stack2string";
		}
	}

}
